package com.geostart.constructionland.system.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.geostart.constructionland.system.entity.RepEntity;
import com.geostart.constructionland.system.entity.indicator.CityPlanIndicatorEntity;
import com.geostart.constructionland.system.mapper.indicator.CityPlanIndicatorMapper;
import com.geostart.constructionland.system.service.indicator.CityPlanIndicatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geostar.constructionland.common.service.dict.JsydDicEntryService;
import com.geostart.constructionland.system.dto.CityPlanIndicatorDTO;

import lombok.extern.slf4j.Slf4j;

/**
 * 市级指标服务类
 *
 * @author chenjianjun
 * @since 2020-09-08 17:54
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CityPlanIndicatorServiceImpl extends ServiceImpl<CityPlanIndicatorMapper, CityPlanIndicatorEntity>
                implements CityPlanIndicatorService {
    @Autowired
    private CityPlanIndicatorMapper cityPlanIndicatorMapper;
    @Autowired
    private JsydDicEntryService dicEntryService;

    @Override
    public RepEntity isRepeatImport(MultipartFile multipartFile) {
        RepEntity repEntity = new RepEntity();
        repEntity.setCode("200");
        // 获取统计日期
        Date excelIndicatorDate = getExcelIndicatorDate(multipartFile);
        if (excelIndicatorDate == null) {
            repEntity.setCode("500");
            repEntity.setContent("获取统计日期失败");
            return repEntity;
        }
        CityPlanIndicatorEntity param = CityPlanIndicatorEntity.builder().indicatorDate(excelIndicatorDate).build();
        List<CityPlanIndicatorEntity> result = this.list(param);
        if (!result.isEmpty()) {
            repEntity.setContent("true");
        } else {
            repEntity.setContent("false");
        }
        return repEntity;
    }

    @Override
    public void cityPlanIndicatorImport(MultipartFile multipartFile, String createUserId, String createUserName,
                    Integer repeatImportFlag) throws Exception {
        ImportParams params = new ImportParams();
        // 第五行获取真实数据
        params.setHeadRows(5);
        List<CityPlanIndicatorEntity> cityPlanIndicatorEntityList = ExcelImportUtil
                        .importExcel(multipartFile.getInputStream(), CityPlanIndicatorEntity.class, params);
        List<CityPlanIndicatorEntity> insetData = new ArrayList<>();
        // 数据字典
        Map<String, String> dictMap = dicEntryService.getDictMap("XZQHDM");
        // 获取统计日期
        Date excelIndicatorDate = getExcelIndicatorDate(multipartFile);
        // 字符串获取日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        // 指标年份
        String indicatorYear = sdf.format(excelIndicatorDate);
        int orderNum = 1;
        for (CityPlanIndicatorEntity cityPlanIndicatorEntity : cityPlanIndicatorEntityList) {
            // 最后一行有备注字样，则不新增
            if (!cityPlanIndicatorEntity.getAdministrativeRegionName().contains("备注")) {
                cityPlanIndicatorEntity.setCreateUserId(createUserId);
                cityPlanIndicatorEntity.setCreateUserName(createUserName);
                cityPlanIndicatorEntity.setIndicatorDate(excelIndicatorDate);
                cityPlanIndicatorEntity.setIndicatorYear(indicatorYear);
                // 保留四位小数
                if (cityPlanIndicatorEntity.getYear2017Cardinality() != null) {
                    cityPlanIndicatorEntity.setYear2017Cardinality(cityPlanIndicatorEntity.getYear2017Cardinality()
                                    .setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                if (cityPlanIndicatorEntity.getYear2017DisposalCount() != null) {
                    cityPlanIndicatorEntity.setYear2017DisposalCount(cityPlanIndicatorEntity.getYear2017DisposalCount()
                                    .setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                if (cityPlanIndicatorEntity.getYear2018Cardinality() != null) {
                    cityPlanIndicatorEntity.setYear2018Cardinality(cityPlanIndicatorEntity.getYear2018Cardinality()
                                    .setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                if (cityPlanIndicatorEntity.getYear2018DisposalCount() != null) {
                    cityPlanIndicatorEntity.setYear2018DisposalCount(cityPlanIndicatorEntity.getYear2018DisposalCount()
                                    .setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                if (cityPlanIndicatorEntity.getIdleCardinality() != null) {
                    cityPlanIndicatorEntity.setIdleCardinality(
                                    cityPlanIndicatorEntity.getIdleCardinality().setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                if (cityPlanIndicatorEntity.getIdleDisposalCount() != null) {
                    cityPlanIndicatorEntity.setIdleDisposalCount(cityPlanIndicatorEntity.getIdleDisposalCount()
                                    .setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                if (cityPlanIndicatorEntity.getIndicatorNum() != null) {
                    cityPlanIndicatorEntity.setIndicatorNum(
                                    cityPlanIndicatorEntity.getIndicatorNum().setScale(4, BigDecimal.ROUND_HALF_UP));
                }
                // 根据数据字典名获取code
                if (dictMap.containsKey(cityPlanIndicatorEntity.getAdministrativeRegionName())) {
                    cityPlanIndicatorEntity.setAdministrativeRegionCode(
                                    dictMap.get(cityPlanIndicatorEntity.getAdministrativeRegionName()));
                }
                cityPlanIndicatorEntity.setOrderNum(orderNum);
                orderNum++;
                insetData.add(cityPlanIndicatorEntity);
            } else {
                break;
            }
        }
        // 是否覆盖导入
        if (repeatImportFlag != null && repeatImportFlag.equals(1)) {
            CityPlanIndicatorEntity deleteParam =
                            CityPlanIndicatorEntity.builder().indicatorDate(excelIndicatorDate).build();
            cityPlanIndicatorMapper.delete(deleteParam);
        }
        this.saveBatch(insetData);
    }

    @Override
    public List<CityPlanIndicatorEntity> list(CityPlanIndicatorEntity cityPlanIndicatorEntity) {
        QueryWrapper<CityPlanIndicatorEntity> queryWrapper = new QueryWrapper<>();
        // 日期格式
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String nowDate = format.format(cityPlanIndicatorEntity.getIndicatorDate());
        try {
            queryWrapper.eq("indicator_date", format.parse(nowDate));
            queryWrapper.orderByAsc("order_num");
        } catch (Exception e) {
            log.info("日期格式转换错误");
        }
        return cityPlanIndicatorMapper.selectList(queryWrapper);
    }

    private Date getExcelIndicatorDate(MultipartFile multipartFile) {
        ImportParams params = new ImportParams();
        // 第2行获取真实数据
        params.setHeadRows(1);
        params.setReadRows(1);
        try {
            String indicatorDate = "";
            List<CityPlanIndicatorDTO> cityPlanIndicatorEntityList = ExcelImportUtil
                            .importExcel(multipartFile.getInputStream(), CityPlanIndicatorDTO.class, params);
            if (!cityPlanIndicatorEntityList.isEmpty()) {
                indicatorDate = cityPlanIndicatorEntityList.get(0).getIndicatorDate();
                int numberIndex;
                if (indicatorDate != null && !"".equals(indicatorDate)) {
                    // 获取第一个数字的下标，截取日期
                    for (int i = 0; i < indicatorDate.length(); i++) {
                        if (indicatorDate.charAt(i) >= 48 && indicatorDate.charAt(i) <= 57) {
                            numberIndex = i;
                            indicatorDate = indicatorDate.substring(numberIndex);
                            break;
                        }
                    }
                }
            }
            if (indicatorDate != null) {
                // 字符串获取日期
                SimpleDateFormat sdf = new SimpleDateFormat();
                if (indicatorDate.length() == 8) {
                    sdf = new SimpleDateFormat("yyyy-M-d");
                } else if (indicatorDate.length() == 9) {
                    sdf = new SimpleDateFormat("yyyy-M-dd");
                } else if (indicatorDate.length() == 10) {
                    sdf = new SimpleDateFormat("yyyy-MM-dd");
                }
                return sdf.parse(indicatorDate);
            } else {
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
}
